import json
import time

import requests

from tencent_sdk.tencent_api_test import TencentApiTools


def main():
    now = int(time.time()) * 1000
    thirty_minutes_ago = now - 1000 * 60 * 60 * 6
    print(now)
    print(thirty_minutes_ago)
    data = '{"index":"logs_server*","ignore_unavailable":true}\n{"version":true,"size":500,"sort":[{"@timestamp":{"order":"desc","unmapped_type":"boolean"}}],"_source":{"excludes":[]},"aggs":{"2":{"date_histogram":{"field":"@timestamp","interval":"30s","time_zone":"Asia/Shanghai","min_doc_count":1}}},"stored_fields":["*"],"script_fields":{},"docvalue_fields":[{"field":"@timestamp","format":"date_time"}],"query":{"bool":{"must":[{"match_all":{}},{"match_phrase":{"log":{"query":"403"}}},{"match_phrase":{"kubernetes.pod_name":{"query":"static"}}},{"range":{"@timestamp":{"gte":%(start)s,"lte":%(now)s,"format":"epoch_millis"}}}],"filter":[],"should":[],"must_not":[]}},"highlight":{"pre_tags":["@kibana-highlighted-field@"],"post_tags":["@/kibana-highlighted-field@"],"fields":{"*":{}},"fragment_size":2147483647},"timeout":"30000ms"}\n'
    data = data % dict(now=now, start=thirty_minutes_ago)

    url = "http://172.16.8.63/elasticsearch/_msearch?rest_total_hits_as_int=true&ignore_throttled=true"

    header = {
        "Origin": "http://172.16.8.63",
        "Content-Length": '862',
        "Accept-Language": "en,zh-CN;q=0.9,zh;q=0.8",
        "Accept-Encoding": "gzip, deflate",
        "kbn-version": "6.6.1",
        "Connection": "keep-alive",
        "Accept": "application/json, text/plain, */*",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
        "Host": "172.16.8.63",
        "Referer": "http://172.16.8.63/app/kibana",
        "content-type": "application/x-ndjson"
    }

    data_json = json.dumps(data)
    # print(data_json)
    r = requests.post(url=url, headers=header, data=data)

    if r.status_code != 200:
        print("error! response code is ", r.status_code)
        return

    r_text = r.text
    # print(r_text)
    result_json = json.loads(r_text)
    tencent_cdn_ips = []
    if 'responses' in result_json and 'hits' in result_json['responses'][0]:
        total = result_json['responses'][0]['hits']['total']
        if total > 0:
            print("has ", total, "hits")
            log_list = result_json['responses'][0]['hits']['hits']
            for log in log_list:
                log_nginx = log['_source']['log']
                if '/img' in log_nginx:
                    visitor_ip = log_nginx.split('- -')[0].rstrip()
                    if visitor_ip not in tencent_cdn_ips:
                        tencent_cdn_ips.append(visitor_ip)

        else:
            print("total < 0", total)
    else:
        print("xxxx")
    if len(tencent_cdn_ips) > 0:
        print("find tencent ips ", len(tencent_cdn_ips), tencent_cdn_ips)
        TencentApiTools().describe_cdn_ip(tencent_cdn_ips)
    else:
        print("not found tencent ips")


if __name__ == '__main__':
    main()
